﻿using Service.Utity;
using WorkflowCore.Interface;
using WorkflowCore.Models;

namespace Service.CertWorkFlow.Steps
{
    public class EditDNSRecord : StepBodyAsync
    {
        public override async Task<ExecutionResult> RunAsync(IStepExecutionContext context)
        {
            var data = context.Workflow.Data as WorkflowData;
            var editor = PluginFactory.CreateDNSRecordEditorInstance().FirstOrDefault(s => s.Identity == data.Config.DnsEditorConfig.PluginIdentity);
            editor.Config = data.Config.DnsEditorConfig.Config;
            var rootDomain = DomainHelper.GetRootDomain(data.Config.Domain);
            var subDomain = DomainHelper.GetSubDomain(data.Config.Domain);
            var record = data.Dns01ChallengeValidationDetails.DnsRecordName.Replace($".{rootDomain}","");
            var res = await editor.EditDnsRecord(rootDomain, record, data.Dns01ChallengeValidationDetails.DnsRecordType, data.Dns01ChallengeValidationDetails.DnsRecordValue);
            data.Action?.Invoke(res.Message);
            if (!res.Result)
            {
                throw new Exception(res.Message);
            }
            return ExecutionResult.Next();
        }
    }
}
    